//
//  OSCObjsViewController.m
//  oschina_song
//
//  Created by song on 16/1/26.
//  Copyright © 2016年 song. All rights reserved.
//

#import "OSCObjsViewController.h"
#import "MJRefresh.h"


@interface OSCObjsViewController ()

@property(nonatomic ,strong) AFHTTPRequestOperationManager *manager;

@end



@implementation OSCObjsViewController




-(void)viewDidLoad
{
    
    [super viewDidLoad];
    _manager = [AFHTTPRequestOperationManager OSCManger];
    
    _objects = [NSMutableArray array];
    _label = [UILabel new];
    _label.numberOfLines = 0;
    _label.lineBreakMode = NSLineBreakByWordWrapping;
    _label.font = [UIFont boldSystemFontOfSize:14];
    _manager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    self.tableView.mj_header = ({
        MJRefreshNormalHeader *header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
        header.lastUpdatedTimeLabel.hidden =YES;
        header.stateLabel.hidden = YES;
        header;
    });
    
    
    [self fetchObjectsOnpage:0 refresh:YES];
}

-(void)refresh
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _manager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
        [self fetchObjectsOnpage:0 refresh:YES];
    });
}


-(void)fetchObjectsOnpage:(NSInteger )page  refresh:(BOOL)refresh
{
    [_manager GET:self.generateURL(page) parameters:nil success:^(AFHTTPRequestOperation *  operation, ONOXMLDocument *responseDocument) {
       
        NSLog(@"%@",self.generateURL(page));
        NSArray *objsXML = [self parseXML:responseDocument];
        if(refresh)
        {
            [_objects removeAllObjects];
        }
        for(ONOXMLElement *objXML in objsXML)
        {
            id obj =[[_objclass alloc] initWithXML:objXML];
            [_objects addObject:obj];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if(self.tableView.mj_header.isRefreshing)
            {
                [self.tableView.mj_header endRefreshing];
            }
            [self.tableView reloadData];
        });
 
        
    } failure:^(AFHTTPRequestOperation * operation, NSError *error) {
        NSLog(@"%@",error);
        
        [self.tableView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.objects.count;
}

-(NSArray *)parseXML:(ONOXMLDocument *)xml
{
    
    return nil;
}

@end
